﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Domain.ActiveDirectory.Model;

namespace Domain.ActiveDirectory.Accessor
{
    public class GroupAccessor : Accessor
    {
        public GroupAccessor(Connection connection) 
            : base(connection) { }

        public IEnumerable<Group> GetGroupsByName(IEnumerable<string> groupNames)
        {
            return FilterBy(new List<string>() { "cn" }, groupNames);
        }

        protected virtual IEnumerable<Group> FilterBy(IEnumerable<string> propertyNames, IEnumerable<string> propertyValue)
        {
            string filterString = DetermineSearchString(propertyNames, propertyValue, "(&(objectClass=group)");
            _connection.Searcher.Filter = filterString.ToString();
            _connection.Searcher.PropertiesToLoad.Clear();
            _connection.Searcher.PropertiesToLoad.Add("cn");
            _connection.Searcher.PropertiesToLoad.Add("member");
            _connection.Searcher.PropertiesToLoad.Add("distinguishedname");
            SearchResultCollection groupsFound = _connection.Searcher.FindAll();
            List<Group> groups = new List<Group>();
            foreach (SearchResult result in groupsFound)
            {
                Group group = ConvertSearchResultToGroup(result);
                groups.Add(group);
            }
            return groups.AsEnumerable();
        }

        private Domain.ActiveDirectory.Model.Group ConvertSearchResultToGroup(SearchResult searchResultGroup)
        {
            Group group = new Group();
            string groupName = searchResultGroup.Properties["cn"][0].ToString();
            group.Name = groupName;
            group.MemberNames = GetCommonNames(searchResultGroup.Properties["member"]);
            group.DistinguishedName = searchResultGroup.Properties["distinguishedName"][0].ToString();
            return group;
        }


    }
}
